/**
 * 
 */
package jvs.peer.xmpp;

import jvs.peer.io.MessageConstant;
import jvs.peer.util.Log;

import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;


/**
 * @author qiangli
 *
 */
public class XmppMessageFilter implements PacketFilter {
	public XmppMessageFilter() {
	}

	/**
	 * Only accept normal messages with valid thread, jid, and mode
	 */
	public boolean accept(Packet packet) {
		if (XmppUtil.isLoopback(packet)) {
			return false;
		}
		if (!(packet instanceof Message)) {
			return false;
		} 
		
		Message msg = (Message) packet;
		if (!msg.getType().equals(Message.Type.normal)) {			
			return false;
		}
		
		String tid = msg.getThread();
		String from = msg.getFrom();
		if (tid == null || from == null) {
			return false;
		}
		
		Object mode = msg.getProperty(MessageConstant.mode);
		
		if (mode == null || !(mode.equals(MessageConstant.request) || mode.equals(MessageConstant.response))){
			if (Log.DEBUG) {
				Log.log(this, "unknown mode:"+mode+" from: "+from+" tid: "+tid);
			}
			return false;
		}
		if (Log.DEBUG) {
			Log.log(this,"accepted id: "+packet.getPacketID()+" from: " + msg.getFrom()+" tid: " + tid+" mode: "+mode);
		}
		return true;
	}
}
